package com.cellulam.framework.datasource;

import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;

@Slf4j
public class DataSourceContextHolder {

    private static String DEFAULT_DATASOURCE_NAME = null;
    private static DataSource DEFAULT_DATASOURCE = null;

    public static DataSource getDefaultDatasource() {
        return DEFAULT_DATASOURCE;
    }

    public static String getDefaultDatasourceName() {
        return DEFAULT_DATASOURCE_NAME;
    }

    public static void setDefaultDatasource(String dataSourceName, DataSource dataSource) {
        DEFAULT_DATASOURCE_NAME = dataSourceName;
        DEFAULT_DATASOURCE = dataSource;
    }

    //线程本地环境
    private static final ThreadLocal<String> local = new ThreadLocal<>();

    public static ThreadLocal<String> getLocal() {
        return local;
    }

    public static String getDataSource() {
        return local.get();
    }

    public static void clear() {
        local.remove();
    }

    public static void switchDefaultDataSource() {
        switchDataSource(DEFAULT_DATASOURCE_NAME);
    }

    public static void switchDataSource(String dataSource) {
        local.set(dataSource);
    }
}
